<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* div{
            height: 200px;
            width: 200px;
            border: 2px solid;
        } */
    </style>
</head>
<body>
    <input id='input1' type='text' placeholder='请输入你要发送的消息' />
    <!-- <input id='input2' type='text' placeholder='你的名字' /> -->
    <button onclick="return sendData()">发送请求</button>
    <button onclick="return close()">关闭连接</button>
    <button onclick="return close1()">关闭连接1</button>
    <div id='div1'>消息内容：</div>










    <script>
        //let ws = new WebSocket("ws://10.12.20.40:3000");
        let ws = new WebSocket("ws://localhost:3000");
        let input1 = document.getElementById('input1');
        let input2 = document.getElementById('input2');
        let div1 = document.getElementById('div1');
        const TYPE_ENTER =0;
        const TYPE_LEAVE =1;
        const TYPE_MSG =2;
        
        //连接上服务器时触发此事件
        ws.onopen = function(evt) { 
            console.log("客户端已建立连接到服务器"); 
        };

        //接收到服务器消息时触发此事件
        ws.onmessage = function(evt) {
            console.log( "Received Message: " + evt.data);
            let div1 = document.getElementById('div1');
            let div2 = document.createElement('div');
                //如果直接这样取值将是一个undifined，因为目前的evt.data是一个字符串，它是没有msg属性的；
                //data = evt.data.msg+"----------"+evt.data.time;
                //console.log(evt.data.msg);
            let data = JSON.parse(evt.data) ;
            if(data.type === TYPE_ENTER){
                div2.style.color = 'green';
            }else if(data.type === TYPE_LEAVE){
                div2.style.color = 'red';
            }else if(data.type === TYPE_MSG){
                div2.style.color = 'blue';
            }
            data = data.msg+"-------"+data.time;

            div2.innerHTML = data;

            div1.appendChild(div2);
            //div1.innerHTML= div1.innerHTML+'\n'+evt.data;
        }
        
    

        ws.onerror = function(evt) {
            console.log("Connection error.");
        };

        //接受到服务器发送的close标识时触发此事件
        ws.onclose = function(evt) {
            console.log("Connection closed.");
        };
        
        //上面的是事件，满足条件时触发，send（）是方法，主动发送的；
        function sendData(){
            ws.send(input1.value);
            //ws.send(input2.value);
            input1.value = '';
        };

        //上面的是事件，满足条件时触发，close（）是方法，主动发送的；
        close1 = function(){
            console.log('webscoket is closing!!!');
            ws.close();
        }







    </script>

</body>
</html>